package com.tl.khadmin.service.impl;

import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.tl.khadmin.bean.Staff;
import com.tl.khadmin.bean.Staffrole;
import com.tl.khadmin.bean.Supplier;
import com.tl.khadmin.bean.SupplierBankAccount;
import com.tl.khadmin.mapper.StaffMapper;
import com.tl.khadmin.mapper.StaffroleMapper;
import com.tl.khadmin.mapper.SupplierBankAccountMapper;
import com.tl.khadmin.mapper.SupplierMapper;
import com.tl.khadmin.page.Page;
import com.tl.khadmin.service.StaffIService;
import com.tl.khadmin.util.CommonUtil;
import com.tl.khadmin.util.Constant;
import com.tl.khadmin.util.PutParamUtil;

@Service
public class StaffServiceImpl implements StaffIService{
	
	@Resource
	private StaffMapper staffMapper;
	@Resource
	private SupplierMapper supplierMapper; 
	@Resource
	private StaffroleMapper staffroleMapper;
	@Resource
	private SupplierBankAccountMapper supplierBankAccountMapper;
	
	/**
	 * 供应商设置银行卡信息
	 */
	@Override
	public String saveBankAccountinfo(HttpSession session, SupplierBankAccount supplierBankAccount) {
		Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);  
		if(supplierBankAccount.getId() == null) {
			//新增
			supplierBankAccount.setSupplierId(supplier.getId());
			supplierBankAccount.setCreateTime(new Date());
			supplierBankAccount.setStatus(1);
			int ret = supplierBankAccountMapper.insert(supplierBankAccount);
			session.setAttribute(Constant.USER_SUPPLIER_BANKACCOUNT, supplierBankAccountMapper.findBySupplierId(supplier.getId())); 
			return CommonUtil.returnMapResultByRows(ret, "保存成功", "保存失败，请重试");
		}else{
			//修改  
			//修改需要重新审核
			supplierBankAccount.setStatus(1);
			supplierBankAccount.setUpdateTime(new Date());
			supplierBankAccount.setSupplierId(supplier.getId());
			int row = supplierBankAccountMapper.updateByPrimaryKey(supplierBankAccount);
			session.setAttribute(Constant.USER_SUPPLIER_BANKACCOUNT, supplierBankAccountMapper.findBySupplierId(supplier.getId())); 
			return CommonUtil.returnMapResultByRows( row, "保存成功", "保存失败，请重试"); 
		} 
	}
	
	@Override
	public String saveSupplierInfo(HttpSession session, Supplier supplier){ 
		Supplier temp = new Supplier(); 
		temp.setSupplierName(supplier.getSupplierName());
		temp.setContactName(supplier.getContactName());
		Supplier ses = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);  
		temp.setId(ses.getId());
		int result = supplierMapper.updateByPrimaryKeySelective(temp);
		return CommonUtil.returnMapResultByRows(result, "保存成功", "保存失败，请重试");
	}
	
	@Override
	public Page<Staff> showStaffByPage(HttpSession session, int pageNum, int pageSize, Map<String, Object> params) {
		Page<Staff> page=new Page<Staff>(pageNum, pageSize);
        params.put("page", page);   
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        params.put("supplierId", supplier.getId());
        PutParamUtil.setParamIsInterior(supplier, params);	//设置查询供应商数据范围 
        List<Staff> list=staffMapper.selectByProperyByPage(params);  
		page.setResult(list);
		return page;
	}
	
	@Override
	public String deleteStaff(Integer id) {
		try {
			return CommonUtil.returnMapResultByRows(staffMapper.deleteByPrimaryKey(id), "删除成功", "删除失败");
		} catch (Exception e) { 
			return CommonUtil.returnMapResultByRows(0, "删除成功", "删除异常");
		}  
	}
	
	@Override
	public String saveStaff(HttpSession session, Staff staff) {
		
		Integer id = staffMapper.queryIdByLoginname(staff.getLoginname());
		if (id != null) {
			return CommonUtil.returnMapResultToJson("fail","登录帐号已经存在，请重新设置");
		}
		staff.setPassword(CommonUtil.sign("666666","UTF-8").toLowerCase());
		staff.setCreatetime(new Date());
		staff.setStatus(1); 
		Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);  
		staff.setSupplierId(supplier.getId());
		int result = staffMapper.insert(staff);
		return CommonUtil.returnMapResultByRows(result, "添加成功，初始密码6个6", "添加失败，请重试");
	}
	
	@Override
	public Staff queryById(Integer id) {
		return staffMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public String updateStaff(Staff staff) {

		Staff lastStaff = staffMapper.selectByPrimaryKey(staff.getId());
		lastStaff.setNickname(staff.getNickname());
		lastStaff.setRole(staff.getRole());
		lastStaff.setPhone(staff.getPhone());
		int result = staffMapper.updateByPrimaryKeySelective(lastStaff);
		return CommonUtil.returnMapResultByRows(result, "修改成功","修改失败，请重试");
	}
	
	@Override
	public String updateStaffInfo(HttpSession session,String nickname,String loginname) {
		Staff staff = (Staff) session.getAttribute(Constant.USER);
		List<Staff> list = staffMapper.findStaffByLoginname(loginname,staff.getId());
		if(list!=null && list.size()>0) {
			return CommonUtil.returnMapResultToJson("fail","登录账号已存在，请重新设置");
		}
		Staff lastStaff = staffMapper.selectByPrimaryKey(staff.getId());
		lastStaff.setNickname(nickname);
		lastStaff.setLoginname(loginname);
		int result = staffMapper.updateByPrimaryKeySelective(lastStaff);
		if(result == 1) {
			staff.setNickname(nickname);
			staff.setLoginname(loginname);
		}
		return CommonUtil.returnMapResultByRows(result, "修改成功","修改失败，请重试");
	}
	
	/**
	 * 后台用户登录
	 * 如所属供应商未通过审核，则反馈修改建议
	 */
	@Override
	public String login(HttpSession session, String loginname, String password) {
		if(loginname==null || loginname.equals("") || password==null || password.equals("")){
			return null;
		}
		Staff staff= staffMapper.checkStaff(loginname, password);
		if(staff==null){
			return CommonUtil.returnMapResultToJson("pass_error", "用户名或密码错误");
		}
		//用户状态(0.停用1.启用)
		if(staff.getStatus().intValue() != 1) {
			return CommonUtil.returnMapResultToJson("fail", "账号已被停用");
		}
		//审核状态，1待审核，2审核通过，3审核不通过
		Supplier supplier =supplierMapper.selectByPrimaryKey(staff.getSupplierId());
		//供应商当前状态，1启用，2停用
		if(supplier.getStatus().intValue() == 2){
			return CommonUtil.returnMapResultToJson("fail", "该供应商处于禁用状态，请联系相关人员");
		}
		int auditStatus = supplier.getAuditStatus();
		if(auditStatus == 3) {
			//反馈审核信息
			return CommonUtil.returnMapResultToJson("fail","供应商信息审核不通过，修改建议：" + supplier.getAuditOpinion());
		}else if(auditStatus == 1) {
			//提示待审核中
			return CommonUtil.returnMapResultToJson("fail","供应商信息审核中");
		} 
		session.setAttribute(Constant.USER, staff); 
		session.setAttribute(Constant.USER_SUPPLIER, supplier); 
		session.setAttribute(Constant.USER_SUPPLIER_BANKACCOUNT, supplierBankAccountMapper.findBySupplierId(supplier.getId())); 
		return CommonUtil.returnMapResultToJson("success","登录成功"); 
	}
	
	public String updateState(Integer id,Integer state) {
		int result = staffMapper.updateState(id,state);
		return CommonUtil.result(result);
	}
	
	public String updateDefaultPwd(Staff sessionUser,Integer id) {
//		boolean hasAuthority = Constant.ROLE_SUPER_ADMIN==sessionUser.getRole() 
//				|| Constant.ROLE_ADMIN==sessionUser.getRole();
//		if(!hasAuthority) {
//			return CommonUtil.returnMapResultToJson("fail", "您无权重置密码");
//		}
//		if(password ==null || password.trim()=="" || !CommonUtil.sign(password,"utf-8").toLowerCase().equals(sessionUser.getPassword())) {
//			return CommonUtil.returnMapResultToJson("fail", "当前用户密码输入错误");
//		}
		int result = staffMapper.updateDefaultPwd(id,CommonUtil.sign("666666","utf-8").toLowerCase());
		if(result == 1){
			return CommonUtil.returnMapResultToJson("success", "设置成功");
		}else{
			return CommonUtil.returnMapResultToJson("fail", "设置失败，请重新操作");
		}
	}
	
	public String updatePhone(Staff staff, String oldphone, String newphone) {
		int result = 0;
		if(oldphone.equals(staff.getPhone())) {
			staff.setPhone(newphone);
			result = staffMapper.updateByPrimaryKeySelective(staff);
			if(result == 1) {
				return CommonUtil.returnMapResultToJson("success", "修改成功");
			}
		}else{
			return CommonUtil.returnMapResultToJson("false", "原手机号不正确");
		}
		return CommonUtil.returnMapResultToJson("false", "修改失败，请重试");
	}
	
	public String updatePwd(Integer id, String oldpassword, String newpassword, 
			String confirm_newpassword, String key, HttpSession session) {
		 
		if(StringUtils.isEmpty(oldpassword) || StringUtils.isEmpty(newpassword) 
				|| StringUtils.isEmpty(confirm_newpassword) ) {
			return CommonUtil.returnMapResultToJson("false", "密码或确认密码不能为空");
		}
		if(!newpassword.equals(CommonUtil.sign(confirm_newpassword+key,"utf-8").toLowerCase())) {
			return CommonUtil.returnMapResultToJson("false", "密码与确认密码不一致");
		} 
		Staff user = staffMapper.selectByPrimaryKey(id);
		if (user != null) {
			if (oldpassword.equals(CommonUtil.sign(user.getPassword()+key,"utf-8").toLowerCase())) {  
				user.setPassword(confirm_newpassword); 
				int num = staffMapper.updateByPrimaryKeySelective(user); 
				if (num == 1) {
					Enumeration<String> em = session.getAttributeNames();
					while (em.hasMoreElements()) {
						session.removeAttribute(em.nextElement().toString());
					}
					session.removeAttribute(Constant.USER);
					session.invalidate();
					return CommonUtil.returnMapResultToJson("success", "修改成功");
				}
			}else{
				return CommonUtil.returnMapResultToJson("false", "原始密码不正确");
			}
		}
		return CommonUtil.returnMapResultToJson("false", "修改失败，请重试");
	}

	@Override
	public List<Staffrole> queryStaffRoleName(HttpSession session, Map<String, Object> params) {
		Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
		params.put("supplierId", supplier.getId());
		return staffroleMapper.staffrolelist(params);
	}
	
}